<template>
  <view class="address-edit-page">
    <!-- 页面标题 -->
    <view class="page-header">
      <text class="page-title">{{ isEdit ? '编辑地址' : '新增地址' }}</text>
    </view>

    <!-- 表单内容 -->
    <view class="form-container">
      <!-- 联系人信息 -->
      <view class="form-section">
        <view class="section-title">
          <text class="title-text">联系人信息</text>
        </view>
        
        <view class="form-item">
          <text class="item-label">收货人</text>
          <input 
            class="item-input" 
            type="text" 
            v-model="formData.receiverName"
            placeholder="请输入收货人姓名"
            maxlength="20"
          />
        </view>
        
        <view class="form-item">
          <text class="item-label">手机号</text>
          <input 
            class="item-input" 
            type="number" 
            v-model="formData.receiverPhone"
            placeholder="请输入手机号码"
            maxlength="11"
          />
        </view>
      </view>

      <!-- 地址信息 -->
      <view class="form-section">
        <view class="section-title">
          <text class="title-text">地址信息</text>
        </view>
        
        <view class="form-item picker-item" @tap="showRegionPicker">
          <text class="item-label">所在地区</text>
          <view class="picker-content">
            <text class="picker-text" :class="{ placeholder: !regionText }">{{ regionText || '请选择省市区' }}</text>
            <text class="picker-arrow">></text>
          </view>
        </view>
        
        <view class="form-item">
          <text class="item-label">详细地址</text>
          <textarea 
            class="item-textarea" 
            v-model="formData.detailAddress"
            placeholder="请输入详细地址（街道、门牌号等）"
            maxlength="100"
            :show-count="true"
          ></textarea>
        </view>
      </view>

      <!-- 设置选项 -->
      <view class="form-section">
        <view class="form-item switch-item">
          <text class="item-label">设为默认地址</text>
          <switch 
            class="item-switch" 
            :checked="formData.isDefault" 
            @change="onDefaultChange"
            color="#FFB800"
          />
        </view>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-actions">
      <view class="save-btn" @tap="saveAddress">
        <text class="btn-text">保存地址</text>
      </view>
    </view>

    <!-- 地区选择器 -->
    <picker 
      mode="region" 
      :value="regionValue" 
      @change="onRegionChange"
      class="region-picker"
    >
      <view></view>
    </picker>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import api from '@/utils/api.js'

// 响应式数据
const isEdit = ref(false)
const addressId = ref(null)
const formData = ref({
  receiverName: '',
  receiverPhone: '',
  provinceName: '',
  cityName: '',
  districtName: '',
  detailAddress: '',
  isDefault: false,
  street: '',
  addressLabel: '',
  postalCode: ''
})
const regionValue = ref(['', '', ''])
const loading = ref(false)

// 计算属性
const regionText = computed(() => {
  if (formData.value.provinceName && formData.value.cityName && formData.value.districtName) {
    return `${formData.value.provinceName} ${formData.value.cityName} ${formData.value.districtName}`
  }
  return ''
})

// 加载地址详情（编辑模式）
const loadAddressDetail = async (id) => {
  try {
    const res = await api.address.getAddressDetail(id)
    console.log('地址详情：', res)
    
    if (res.code === 0 && res.data) {
      formData.value = res.data
      regionValue.value = [formData.value.provinceName, formData.value.cityName, formData.value.districtName]
    } else {
      uni.showToast({
        title: res.message || '加载地址失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('加载地址详情失败:', error)
    uni.showToast({
      title: error.message || '加载地址失败',
      icon: 'none'
    })
  }
}

// 显示地区选择器
const showRegionPicker = () => {
  // 触发picker组件
  const picker = document.querySelector('.region-picker picker')
  if (picker) {
    picker.click()
  }
}

// 地区选择变化
const onRegionChange = (e) => {
  const [province, city, district] = e.detail.value
  formData.value.provinceName = province
  formData.value.cityName = city
  formData.value.districtName = district
  regionValue.value = e.detail.value
}

// 默认地址开关变化
const onDefaultChange = (e) => {
  formData.value.isDefault = e.detail.value
}

// 表单验证
const validateForm = () => {
  if (!formData.value.receiverName.trim()) {
    uni.showToast({
      title: '请输入收货人姓名',
      icon: 'none'
    })
    return false
  }
  
  if (!formData.value.receiverPhone.trim()) {
    uni.showToast({
      title: '请输入手机号码',
      icon: 'none'
    })
    return false
  }
  
  // 简单的手机号验证
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!phoneRegex.test(formData.value.receiverPhone)) {
    uni.showToast({
      title: '请输入正确的手机号码',
      icon: 'none'
    })
    return false
  }
  
  if (!formData.value.provinceName || !formData.value.cityName || !formData.value.districtName) {
    uni.showToast({
      title: '请选择所在地区',
      icon: 'none'
    })
    return false
  }
  
  if (!formData.value.detailAddress.trim()) {
    uni.showToast({
      title: '请输入详细地址',
      icon: 'none'
    })
    return false
  }
  
  return true
}

// 保存地址
const saveAddress = async () => {
  if (!validateForm()) {
    return
  }
  
  loading.value = true
  
  try {
    // 构建提交数据，映射到数据库字段
    const submitData = formData.value
    
    // 获取openId
    const openId = uni.getStorageSync('openid')
    if (!openId) {
      uni.showToast({
        title: '用户信息获取失败，请重新登录',
        icon: 'none'
      })
      loading.value = false
      return
    }
    submitData.openId = openId
    let result
    if (isEdit.value) {
      // 编辑模式
      result = await api.address.updateAddress(submitData)
    } else {
      // 新增模式
      result = await api.address.createAddress(submitData, openId)
    }
    
    console.log('保存地址结果：', result)
    
    if (result.code === 0) {
      uni.showToast({
        title: isEdit.value ? '修改成功' : '添加成功',
        icon: 'success'
      })
      
      // 通知地址列表页面刷新
      uni.$emit('addressUpdated')
      
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    } else {
      uni.showToast({
        title: result.message || '保存失败',
        icon: 'none'
      })
    }
    
  } catch (error) {
    console.error('保存地址失败:', error)
    uni.showToast({
      title: '保存失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 生命周期
onLoad((options) => {
  if (options.id) {
    isEdit.value = true
    addressId.value = options.id
    loadAddressDetail(options.id)
  }
})
</script>

<style scoped>
.address-edit-page {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 80px;
}

/* 页面标题 */
.page-header {
  background: white;
  padding: 20px;
  text-align: center;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.page-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

/* 表单容器 */
.form-container {
  padding: 16px;
}

.form-section {
  background: white;
  border-radius: 12px;
  margin-bottom: 16px;
  overflow: hidden;
}

.section-title {
  padding: 16px 20px 12px;
  border-bottom: 1px solid #f0f0f0;
}

.title-text {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.form-item {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
}

.form-item:last-child {
  border-bottom: none;
}

.item-label {
  flex: 0 0 80px;
  font-size: 14px;
  color: #333;
}

.item-input {
  flex: 1;
  font-size: 14px;
  color: #333;
  text-align: right;
}

.item-textarea {
  flex: 1;
  font-size: 14px;
  color: #333;
  min-height: 80px;
  text-align: right;
}

.picker-item {
  
}

.picker-content {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 8px;
}

.picker-text {
  font-size: 14px;
  color: #333;
}

.picker-text.placeholder {
  color: #999;
}

.picker-arrow {
  font-size: 14px;
  color: #999;
}

.switch-item {
  
}

.item-switch {
  
}

/* 底部操作栏 */
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 16px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 100;
}

.save-btn {
  background: linear-gradient(135deg, #FFB800 0%, #FFA000 100%);
  border-radius: 24px;
  padding: 14px 24px;
  text-align: center;
  box-shadow: 0 4px 12px rgba(255, 184, 0, 0.3);
  transition: all 0.3s ease;
}

.save-btn:active {
  transform: translateY(1px);
  box-shadow: 0 2px 8px rgba(255, 184, 0, 0.3);
}

.btn-text {
  font-size: 16px;
  color: white;
  font-weight: bold;
}

/* 隐藏的地区选择器 */
.region-picker {
  position: absolute;
  left: -9999px;
  opacity: 0;
}
</style>